package com.ncmmall.application.securitys.role;

import com.ncmmall.domain.security.auth.Authority;
import com.ncmmall.domain.security.auth.AuthorityRepository;
import com.ncmmall.domain.security.auth.QAuthority;
import com.ncmmall.domain.security.nav.Navigation;
import com.ncmmall.domain.security.nav.NavigationRepository;
import com.ncmmall.domain.security.nav.QNavigation;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.ncmmall.domain.security.role.QRoleAuthority;
import com.ncmmall.domain.security.role.Role;
import com.ncmmall.domain.security.role.RoleAuthority;
import com.ncmmall.domain.security.role.RoleAuthorityRepository;
import com.ncmmall.domain.security.role.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author linxs
 *         系统角色管理
 */
@Service
@Transactional
public class RoleApplication {

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private RoleAuthorityRepository roleAuthorityRepository;

    @Autowired
    private NavigationRepository navigationRepository;

    @Autowired
    private AuthorityRepository authorityRepository;

    @Autowired
    private QueryChannelService queryChannelService;

    /**
     * 添加角色
     *
     * @param role
     */
    public void create(Role role) {
        roleRepository.save(role);
        List<Long> authorityIds = new ArrayList<Long>(role.getAuthoritys().values());

        for (Long authorityId : authorityIds) {

            RoleAuthority item = new RoleAuthority();
            item.setAuthoritysId(authorityId);
            item.setRoleId(role.getId());
            roleAuthorityRepository.save(item);

        }
    }


    /**
     * 修改角色信息
     *
     * @param role
     */
    public void modify(Role role) {
        roleRepository.save(role);
    }


    /**
     * 删除角色
     *
     * @param role
     */
    public void remove(Role role) {
        authorityRepository.delete(queryChannelService.findAll(QAuthority.authority.navigation.role.id.eq(role.getId()), Authority.class));
        navigationRepository.delete(queryChannelService.findAll(QNavigation.navigation.role.id.eq(role.getId()), Navigation.class));
        roleAuthorityRepository.delete(queryChannelService.findAll(QRoleAuthority.roleAuthority.roleId.eq(role.getId()), RoleAuthority.class));
        roleRepository.delete(role);
    }
}
